//
//  ChatViewCell.m
//  BaiYing_Thinker
//
//  Created by 鹏 朱 on 15/11/4.
//  Copyright (c) 2015年 XKJH. All rights reserved.
//

#import "ChatViewCell.h"
#import "SessonContentMessage.h"
#import "XKO_CreateUIViewHelper.h"
#import "UIColor+UIImage.h"
#import "PluginComponentController.h"
#import "FileMangeHelper.h"
#import "SDWebImageManager+MJ.h"
#import "MJPhotoBrowser.h"
#import "MJPhoto.h"
#import "PlayerHelper.h"

@interface ChatViewCell()

@property(nonatomic, strong) PluginComponentController *pluginComponent;
@property (nonatomic, strong) NSTextAttachment *attch;

@end

@implementation ChatViewCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier dataModelType:(DataModelType)dataModelType webSize:(CGSize)webSize
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
        self.contentView.backgroundColor = kGetColor(18, 38, 74);
        self.selectionStyle = UITableViewCellSelectionStyleNone;

        _webSize = webSize;
        _dataModelType = dataModelType;
        if (dataModelType == TextDataModelType) {
            
            [self.contentView addSubview:self.textContent];
            
        } else if (dataModelType == ImageDataModelType) {
            
            [self.contentView addSubview:self.imageContent];
            
        } else if (dataModelType == VideoDataModelType) {
            
            [self.contentView addSubview:self.videoContent];
            
        } else if (dataModelType == AudioDataModelType) {
            
            [self.contentView addSubview:self.textContent];
            
        } else if (dataModelType == WebDataModelType) {
            
            [self.contentView addSubview:self.webContent];
            
        } else if (dataModelType == TextAndImageDataModelType) {
            
            [self.contentView addSubview:self.textContent];
            [self.contentView addSubview:self.imageContent];
            
        }
    }
    
    return self;
}

#pragma mark - getter

- (NSTextAttachment *)attch {
    
    if (!_attch) {
        // 添加表情
        _attch = [[NSTextAttachment alloc] init];
        // 表情图片
        _attch.image = [UIImage imageNamed:@"horn"];
        // 设置图片大小
        _attch.bounds = CGRectMake(0, 0, 15, 15);
    }
    
    return _attch;
}

- (NIAttributedLabel *)textContent {
    
    if (!_textContent) {
        
        _textContent = [[NIAttributedLabel alloc] initWithFrame:CGRectZero];
        _textContent.delegate = self;
        _textContent.textColor = [UIColor whiteColor];
        _textContent.font = kFontSize14;
        _textContent.linkColor = [UIColor whiteColor];
        _textContent.highlightedLinkBackgroundColor = [UIColor clearColor];
        _textContent.linksHaveUnderlines = NO;
        _textContent.numberOfLines = 0;
        [_textContent setUserInteractionEnabled:YES];
    }
    
    return _textContent;
}

- (UIImageView *)imageContent {
    
    if (!_imageContent) {
        _imageContent = [XKO_CreateUIViewHelper createUIImageViewWithImage:[[UIColor grayColor] translateIntoImage]];
        _imageContent.tag = 100;
        _imageContent.userInteractionEnabled = YES;
        
        UITapGestureRecognizer *singleFingerOne  = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(magnifyImage:)];
        singleFingerOne.numberOfTouchesRequired = 1; //手指数
        singleFingerOne.numberOfTapsRequired = 1; //tap次数
        [_imageContent addGestureRecognizer:singleFingerOne];
    }
    
    return _imageContent;
}

- (PluginComponentController *)pluginComponent {
    
    if (!_pluginComponent) {
        
        _pluginComponent = [[PluginComponentController alloc] init];
        
    }
    
    return _pluginComponent;
}

- (UIView *)webContent {
    
    if (!_webContent) {

        _webContent = self.pluginComponent.view;
    }
    
    return _webContent;
}

- (UIView *)videoContent {
    
    if (!_videoContent) {
        
        _videoContent = [[UIView alloc] initWithFrame:CGRectZero];
    }
    
    return _videoContent;
}

- (UIView *)audioContent {
    
    if (!_audioContent) {
        
        _audioContent = [[UIView alloc] initWithFrame:CGRectZero];
    }
    
    return _audioContent;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)setMessage:(SessonContentMessage *)message
{
    if (_message != message) {
        _message = message;
        _cellFrame = [[ChatViewCellFrame alloc] initWithDataModel:message dataModelType:_dataModelType webSize:_webSize];
        
        if (_dataModelType == TextDataModelType) {
            
            [self.textContent setFrame:_cellFrame.textRect];
            [self.textContent setText:message.msg_content];
            [_textContent addLink:nil range:NSMakeRange(0, message.msg_content.length - 1)];
            
            if ([message.isMyself isEqual:@1]) {
                
                if (_cellFrame.textRect.size.height >= 17) {
                    self.textContent.textAlignment = NSTextAlignmentLeft;
                } else {
                    self.textContent.textAlignment = NSTextAlignmentRight;
                }
            } else {
                self.textContent.textAlignment = NSTextAlignmentLeft;
            }
            
        } else if (_dataModelType == ImageDataModelType) {
            
            [self.imageContent setFrame:_cellFrame.imageRect];
            
            //判断是自己发的消息还是收到的消息
            if (IsEmpty(message.local_Path)) {
                
                WEAK_SELF
                
                [self.imageContent sd_setImageWithURL:[NSURL URLWithString:message.content_url] placeholderImage:[[UIColor grayColor] translateIntoImage] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                    
                    //调整高度
                    CGSize imgRect = [Util resetImageSizeFromSourceSize:image.size maxWidth:KImageWidth maxHeight:KImageHeight];
                    
                    float newHeight = kEdgeInsetTop + kEdgeInsetTop + imgRect.height;
                    if ((int)weak_self.frame.size.height != (int)newHeight) {
                        
                        if (weak_self.webFinishLoadBlock) {
                            weak_self.webFinishLoadBlock(NSStringFromCGSize(imgRect),message.session_content_id);
                        }
                    }
                }];
                
            } else {
                
                //从本地加载图片
                NSString *localPath = [[FileMangeHelper shareInstance] getUploadFilePathFromFileType:UploadFileImageType fileName:message.local_Path];
                UIImage *image = [UIImage imageWithContentsOfFile:localPath];
                [self.imageContent setImage:image];
            }
            
        } else if (_dataModelType == VideoDataModelType) {
            
            [self.videoContent setFrame:_cellFrame.videoRect];
            
        } else if (_dataModelType == AudioDataModelType) {
            
            [self.textContent setFrame:_cellFrame.textRect];
            [self.textContent setText:[NSString stringWithFormat:@"%@ ",message.msg_content]];
            [self.textContent insertImage:[UIImage imageNamed:@"horn"] atIndex:self.textContent.text.length];
//            NSInteger length = (self.textContent.text.length>3)?4:self.textContent.text.length;
//            NSInteger location = (self.textContent.text.length>3)?(self.textContent.text.length-4):0;
//            [_textContent addLink:nil range:NSMakeRange(location, length)];
            [_textContent addLink:nil range:NSMakeRange(0, self.textContent.text.length - 1)];

            if ([message.isMyself isEqual:@1]) {
                
                if (_cellFrame.textRect.size.height >= 17) {
                    self.textContent.textAlignment = NSTextAlignmentLeft;
                } else {
                    self.textContent.textAlignment = NSTextAlignmentRight;
                }
            } else {
                self.textContent.textAlignment = NSTextAlignmentLeft;
            }
            
        } else if (_dataModelType == WebDataModelType) {
            
            NSString *path = [[FileMangeHelper shareInstance] getDownloadHtmlFilePathFromFileType:UploadFileZipType documentName:message.local_Path];
            
            WEAK_SELF
            [self.pluginComponent reinitWithFrame:CGRectMake(kEdgeInsetLeft, kEdgeInsetTop, _cellFrame.webRect.size.width, _cellFrame.webRect.size.height) path:path rule:message.componentRule finishLoadBlock:^(CGSize size) {
                
                float newHeight = kEdgeInsetTop + kEdgeInsetTop + size.height;
                if ((int)weak_self.frame.size.height != (int)newHeight) {
                    
                    if (weak_self.webFinishLoadBlock) {
                        weak_self.webFinishLoadBlock(NSStringFromCGSize(size),weak_self.message.session_content_id);
                    }
                }
            }];
            
        } else if (_dataModelType == TextAndImageDataModelType) {
            
            [self.textContent setFrame:_cellFrame.textRect];
            [self.textContent setText:message.msg_content];
            [self.imageContent setFrame:_cellFrame.imageRect];
            
        }
    }
}

/**
 *  点击放大图片
 *
 *  @param tap 手势view
 */
- (void)magnifyImage:(UITapGestureRecognizer*)tap
{
    // 1.封装图片数据
    NSMutableArray *photos = [[NSMutableArray alloc] init];
    
    MJPhoto *photo = [[MJPhoto alloc] init];
    
    if (IsEmpty(_message.local_Path)) {
        photo.url = [NSURL URLWithString:_message.content_url]; // 图片路径
    } else {
        NSString *localPath = [[FileMangeHelper shareInstance] getUploadFilePathFromFileType:UploadFileImageType fileName:_message.local_Path];
        UIImage *image = [UIImage imageWithContentsOfFile:localPath];
        photo.image = image;
    }
    photo.srcImageView = (UIImageView *)tap.view; // 来源于哪个UIImageView
    [photos addObject:photo];
    
    // 2.显示相册
    MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
    browser.currentPhotoIndex = tap.view.tag - 100; // 弹出相册时显示的第一张图片是？
    browser.photos = photos; // 设置所有的图片
    [browser show];
}

#pragma mark- NIAttributedLabelDelegate

- (void)attributedLabel:(NIAttributedLabel *)attributedLabel didSelectTextCheckingResult:(NSTextCheckingResult *)result atPoint:(CGPoint)point {
    
    //播放声音
    if ([_message.isMyself isEqual:@1]) {
        
        if (IsEmpty(_message.local_Path)) {
            
            if (_pictureDidSelectedBlock) {
                _pictureDidSelectedBlock(_message.msg_content);
            }
            
        } else {
            NSString *localUrl = AliFile(_message.local_Path);
            
            [[PlayerHelper shared] playVoiceOfUrlString:localUrl finishBlock:^{
            }];
            
        }
        
    } else {
        
        if (IsEmpty(_message.content_url)) {
            
            if (_pictureDidSelectedBlock) {
                _pictureDidSelectedBlock(_message.msg_content);
            }
            
        } else {
            
            [[PlayerHelper shared] playVoiceOfUrlString:_message.content_url finishBlock:^{
            }];
            
        }
    }
}

- (BOOL)attributedLabel:(NIAttributedLabel *)attributedLabel shouldPresentActionSheet:(UIActionSheet *)actionSheet withTextCheckingResult:(NSTextCheckingResult *)result atPoint:(CGPoint)point {
    
    return YES;
}

@end
